<template>
  <div>
    <el-form
      v-if="loginForm.loginType === 'userName'"
      ref="loginForm"
      class="login-form"
      status-icon
      :rules="loginRules"
      :model="loginForm"
      label-width="0"
    >
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.userName"
          auto-complete="off"
          :placeholder="$t('user')+$t('name')"
          @keyup.enter.native="handleLogin"
        >
          <i
            v-if="gzhLogin"
            slot="suffix"
            class="fa fa-weixin el-input__icon"
            @click="loginForm.loginType = 'qrcode'"
          />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          :type="passwordType"
          auto-complete="off"
          :placeholder="$t('password')"
          @keyup.enter.native="handleLogin"
        >
          <i
            slot="suffix"
            class="el-icon-view el-input__icon"
            @click="showPassword"
          />
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-row :span="24">
          <el-col :span="16">
            <el-input
              v-model="loginForm.code"
              auto-complete="off"
              :placeholder="$t('verificationCode')"
              @keyup.enter.native="handleLogin"
            >
              <i
                slot="prefix"
                class="icon-yanzhengma"
              />
            </el-input>
          </el-col>
          <el-col :span="8">
            <div class="login-code">
              <div id="code" class="login-code-img" />
            </div>
          </el-col>
        </el-row>

      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          class="login-submit"
          @click.native.prevent="handleLogin"
        >{{ $t('login') }}
        </el-button>
      </el-form-item>
      <el-checkbox v-model="safeModel" @change="safeModelChange">{{ $t('safe')+$t('model') }}</el-checkbox>
      <el-button type="text" style="float: right" @click="resetPassword = true">{{ $t('reset') + $t('password') }}</el-button>
    </el-form>
    <div v-else="" class="login-form">
      <i class="el-icon-back" @click="userNameType" />
      <login-qrcode style="width: 100%;height: 100%" @change="qrcodeLogin" />
    </div>

    <el-dialog
      :title="$t('reset') + $t('password')"
      :visible.sync="resetPassword"
      width="600px"
    >
      <reset-password v-if="resetPassword" />
    </el-dialog>
  </div>
</template>

<script>
import LoginQrcode from './components/LoginQrcode'
import LanguageSelect from '@/components/LanguageSelect'
import { getGVerify } from '@/util/login-code'
import { validUsername } from '@/util/validate'
import { failureNotice } from '../../util/common'
import ResetPassword from './components/ResetPassword'
import {
  getAppVersion,
  getShortCompanyName,
  getLanguage,
  getCompanyId,
  setLoginFrom,
  getForReferenceInfo, setSafeModel, getSafeModel
} from '@/util/storage'
import { listCompanyResource } from '@/api/iot/iotCompanyResourceApi'
import { existToken } from '@/api/iot/iotThirdPartyTokenApi'
export default {
  name: 'Login',
  components: {
    LanguageSelect,
    LoginQrcode,
    ResetPassword
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      resetPassword: false,
      forReferenceInfo: getForReferenceInfo(),
      gzhLogin: false,
      slideshow: [
        'https://iot.ztn-tech.com/resource/login_carousel/login_carousel1.png'
      ],
      appVersion: getAppVersion(),
      verifyCode: null,
      shortCompanyName: getShortCompanyName(),
      loginForm: {
        userName: '',
        password: '',
        authCode: null,
        code: null,
        loginType: 'userName',
        ticket: null
      },
      model: 'login',
      loginRules: {
        userName: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      redirect: undefined,
      otherQuery: {},
      companyId: getCompanyId(),
      tryLoginNum: 0,
      safeModel: getSafeModel()
    }
  },
  watch: {
    $route: {
      handler(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    this.$i18n.locale = getLanguage() || 'zh'
    this.listCompanyResource()
    this.existToken()

    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    this.verifyCode = getGVerify('code')
  },
  methods: {
    safeModelChange() {
      setSafeModel(this.safeModel)
    },
    existToken() {
      existToken({
        companyId: this.companyId,
        type: 'gzh'
      }).then(res => {
        const { code } = res
        if (code === '200') {
          this.gzhLogin = true
        }
      })
    },
    listCompanyResource() {
      listCompanyResource({
        type: 'phoneSlideshow',
        companyId: this.companyId,
        status: true
      }).then(res => {
        if (res.code === '200') {
          const slideshow = []
          for (const item of res.data) {
            slideshow.push(item.url)
          }
          this.slideshow = slideshow
        }
      })
    },
    userNameType() {
      this.loginForm.loginType = 'userName'
      this.$nextTick(() => {
        this.verifyCode = getGVerify('code')
      })
    },
    showPassword() {
      this.passwordType === ''
        ? (this.passwordType = 'password')
        : (this.passwordType = '')
    },
    modelChange() {
      if (this.model === 'login') {
        this.$nextTick(function() {
          this.verifyCode = getGVerify('code')
        })
      }
    },
    qrcodeLogin(data) {
      this.loginForm.ticket = data
      this.qrcodeLoginFunction()
    },
    qrcodeLoginFunction() {
      this.$store
        .dispatch('user/login', this.loginForm)
        .then(() => {
          this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
        })
        .catch(() => {
          if (this.tryLoginNum < 15) {
            setTimeout(() => {
              this.tryLoginNum = this.tryLoginNum + 1
              this.qrcodeLoginFunction()
            }, 2000)
          } else {
            this.tryLoginNum = 0
            failureNotice(this, null, 10000)
          }
        })
    },
    handleLogin() {
      if (!this.loginForm.isDemoAccount) {
        if (
          !this.loginForm.code ||
            !this.verifyCode.validate(this.loginForm.code)) {
          failureNotice(this, '验证码错误')
          return false
        }
        setLoginFrom('user')
      } else {
        setLoginFrom('demo')
      }

      this.$refs.loginForm.validate(valid => {
        if (valid || this.loginForm.isDemoAccount) {
          this.loading = true
          this.$store
            .dispatch('user/login', this.loginForm)
            .then(() => {
              console.log(this.redirect)
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch((info) => {
              if (info) {
                failureNotice(this, this.$t(info))
              }
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }

  }
}
</script>
